package lk.week02;

import commons.ListNode;

/**
 * ClassName: P0234_HwNodeList
 * Description:
 * Author: xyf
 * Date: 5/21/23 10:59 AM
 * Version: 1.0
 **/
public class P0234_HwNodeList
{
    public boolean isPalindrome(ListNode head)
    {
        if (head == null || head.next == null)
        {
            return true;
        }

        ListNode slow = head;
        ListNode fast = head;
        while (fast != null)
        {
            fast = fast.next.next;
            slow = slow.next;
        }

        ListNode reverseNode = reverse(slow);

        while (reverseNode != null)
        {
            if (reverseNode.val != head.val)
            {
                return false;
            }
            reverseNode = reverseNode.next;
            head = head.next;
        }
        return true;

    }

    ListNode reverse(ListNode head)
    {
        if (head == null)
        {
            return null;
        }

        ListNode pre = null;
        ListNode cur = head;
        while (cur != null)
        {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}